﻿using SLClient.CustomerControls;
using SLClient.Extension;
using SLClient.ServiceAPI;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using SLClient.ViewModels;
using System.ComponentModel;


namespace SLClient.Views
{
    public partial class MainFrame : UserControl
    {
        private DispatcherTimer _dispatcherTimer;
        private Visibility _lastVisiblityH;
        private Visibility _lastVisiblityV;

        public MainFrame()
        {
            this.InitializeComponent();
            ShowMsgs = new ObservableCollection<ShowMsg>();
            MainStackPanel = this.msgList;
            MainMediaElement = this.msg_mp3;
            this.scrollView.LayoutUpdated += new EventHandler(this.ScrollViewLayoutUpdated);
            this.loginView.LoginSuccess += new EventHandler(this.loginView_LoginSuccess);

            //修正by kevin start ==============================
            if (App.Current.IsRunningOutOfBrowser)
            {
                App.Current.MainWindow.Closing += MainWindowClosing;
            }

            //end =============================================
        }

        //修正by kevin start ==============================
        private bool _isLoginOut = false;
        void MainWindowClosing(object sender, System.ComponentModel.ClosingEventArgs e)
        {
            if (!_isLoginOut)
            {
                e.Cancel = true;
                ServiceClient instance = WCFServicesUtil<ServiceClient>.GetInstance(ServiceType.ServiceAPI);
                instance.LoginOutCompleted += delegate(object obj, AsyncCompletedEventArgs arg)
                {
                    _isLoginOut = true;
                    App.Current.MainWindow.Close();
                    (Application.Current.RootVisual as MainFrame).Initlogin();
                };
                instance.LoginOutAsync(ViewDispatcher.LoginUser.UserId);
            }
        }
        //end =============================================

        private void DispatcherTimerTick(object sender, EventArgs e)
        {
            MainMediaElement.Stop();
            GetIncomeMessage();
        }

        public static void GetIncomeMessage()
        {
            ServiceClient serviceClient = WCFServicesUtil<ServiceClient>.GetInstance(ServiceType.ServiceAPI);
            serviceClient.GetUserByUserIdCompleted += delegate(object obj, GetUserByUserIdCompletedEventArgs arg)
            {
                ViewDispatcher.LoginUser.ActivityMoney = arg.Result.ActivityMoney;
                ViewDispatcher.LoginUser.FreezeMoney = arg.Result.FreezeMoney;
                ViewDispatcher.LoginUser.TotleMoney = arg.Result.TotleMoney;
            };
            serviceClient.GetProfitMessageByUserIdCompleted += delegate(object obj, GetProfitMessageByUserIdCompletedEventArgs arg)
            {
                if (arg.Result.Count != 0)
                {
                    ShowMsg msg;
                    ShowMsgs.Clear();
                    List<ProfitList> list = Enumerable.ToList<ProfitList>(arg.Result);
                    List<ProfitList> list2 = Enumerable.ToList<ProfitList>(Enumerable.Where<ProfitList>(list,
                         new Func<ProfitList, bool>((s) => { return (s.ProfitType == "充值"); })
                        ));
                    List<ProfitList> list3 = Enumerable.ToList<ProfitList>(Enumerable.Where<ProfitList>(list,
                         new Func<ProfitList, bool>((s) => { return (s.ProfitType == "盈亏"); })
                        ));

                    List<ProfitList> list4 = Enumerable.ToList<ProfitList>(Enumerable.Where<ProfitList>(list,
                         new Func<ProfitList, bool>((s) => { return (s.ProfitType == "提现"); })
                        ));
                    if (list2.Count != 0)
                    {
                        int num = (int)Enumerable.Sum<ProfitList>(list2,
                             new Func<ProfitList, decimal?>((s) => { return s.Profit; })).Value;
                        ShowMsg msg2 = new ShowMsg
                        {
                            MsgType = 1,
                            Title = "系统消息",
                            Content = string.Format("网银充值{0:F2}元已经到账", num),
                            MsgTime = Enumerable.LastOrDefault<ProfitList>(list2).CreateTime.Value
                        };
                        msg = msg2;
                        ShowMsgs.Add(msg);
                    }
                    if (list4.Count != 0)
                    {
                        decimal? nullable = Enumerable.Sum<ProfitList>(list4, new Func<ProfitList, decimal?>((s) => { return s.Profit; }));
                        decimal? nullable3 = nullable.HasValue ? new decimal?(-nullable.GetValueOrDefault()) : null;
                        int num2 = (int)nullable3.Value;
                        ShowMsg msg3 = new ShowMsg
                        {
                            MsgType = 1,
                            Title = "提现消息",
                            Content = string.Format("提现{0:F2}元已经处理", num2),
                            MsgTime = Enumerable.LastOrDefault<ProfitList>(list4).CreateTime.Value
                        };
                        msg = msg3;
                        ShowMsgs.Add(msg);
                    }
                    if (list3.Count > 0)
                    {
                        var enumerable2 = Enumerable.Select(Enumerable.GroupBy(Enumerable.Select(list3,
                                                              (s) =>
                                                              {
                                                                  return new
                                                                  {
                                                                      Lottery = s.Remark.Substring(0, 3).Replace('[', ' '),
                                                                      OpenNum = s.Remark.Split(new char[] { '-' })[0].Substring(s.Remark.Split(new char[] { '-' })[0].LastIndexOf('[')).Replace("[", " ").Replace("]", " "),
                                                                      Profit = s.Profit,
                                                                      CreateTime = s.CreateTime
                                                                  };
                                                              }),
                                                             (x) => { return new { Lottery = x.Lottery, OpenNum = x.OpenNum }; }),
                                                             (g, s) => { return new { Name = g.Key, Profit = Enumerable.Sum(g, (k) => { return k.Profit; }), Count = Enumerable.Count(g), CreateTime = Enumerable.First(g).CreateTime }; }
                                                              );
                        foreach (var type in enumerable2)
                        {
                            ShowMsg msg5 = new ShowMsg
                            {
                                Title = "盈亏提示",
                                Content = string.Format("{0}{1}派彩结束\r\n您共有{2}条投注记录\r\n本期净盈亏{3:F2}", new object[] { type.Name.Lottery, type.Name.OpenNum, type.Count, type.Profit }),
                                MsgTime = type.CreateTime.Value
                            };
                            ShowMsg item = msg5;
                            ShowMsgs.Add(item);
                        }
                    }
                    SetMsg(ShowMsgs, MainMediaElement, MainStackPanel);
                }
                serviceClient.GetUserByUserIdAsync(ViewDispatcher.LoginUser.UserId);
            };
            serviceClient.GetProfitMessageByUserIdAsync(ViewDispatcher.LoginUser.UserId);
        }

        public void GetMsg()
        {
            ServiceClient instance = WCFServicesUtil<ServiceClient>.GetInstance(ServiceType.ServiceAPI);
            instance.GetUnShownMoneyInRecordsCompleted += delegate(object obj, GetUnShownMoneyInRecordsCompletedEventArgs arg)
            {
                if (arg.Result.Count != 0)
                {
                    ShowMsgs.Clear();
                    foreach (MoneyInHistory history in arg.Result)
                    {
                        ShowMsg msg2 = new ShowMsg
                        {
                            MsgType = 1,
                            Title = "充值提醒",
                            Content = string.Format("你充值的{0}元已经到账", history.Amount),
                            MsgTime = history.CreateTime,
                            ID = history.Id
                        };
                        ShowMsg item = msg2;
                        ShowMsgs.Add(item);
                    }
                    SetMsg(ShowMsgs, MainMediaElement, MainStackPanel);
                }
            };
            if (ViewDispatcher.LoginUser != null)
            {
                instance.GetUnShownMoneyInRecordsAsync(ViewDispatcher.LoginUser.UserId);
            }
        }

        public void Initlogin()
        {
            this.LayoutRoot.Children.Clear();
            LoginView view = new LoginView();
            this.msgList.Children.Clear();
            view.LoginSuccess += new EventHandler(this.loginView_LoginSuccess);
            this.LayoutRoot.Children.Add(view);
        }

        private void loginView_LoginSuccess(object sender, EventArgs e)
        {
            this.LayoutRoot.Children.Clear();
            this.LayoutRoot.Children.Add(new MainpageView());
            MainMediaElement.Stop();
            GetIncomeMessage();
            this._dispatcherTimer = new DispatcherTimer();
            this._dispatcherTimer.Interval = new TimeSpan(0, 1, 30);
            this._dispatcherTimer.Tick += new EventHandler(this.DispatcherTimerTick);
            this._dispatcherTimer.Start();
        }

        public void RemoveKeys()
        {
            TimeSpan span = (TimeSpan)(DateTime.Now - ViewDispatcher.IsExpried);
            if (span.TotalHours > 0.5)
            {
                IsolatedStorageSettings.ApplicationSettings.Remove("News");
                IsolatedStorageSettings.ApplicationSettings.Remove("Banks");
                IsolatedStorageSettings.ApplicationSettings.Remove("SiteConfig");
                IsolatedStorageSettings.ApplicationSettings.Remove("PlayInfos");
            }
        }

        private void ScrollViewLayoutUpdated(object sender, EventArgs e)
        {
            if ((this.scrollView.ComputedVerticalScrollBarVisibility != this._lastVisiblityV) || (this.scrollView.ComputedHorizontalScrollBarVisibility != this._lastVisiblityH))
            {
                double num;
                double num2;
                this._lastVisiblityV = this.scrollView.ComputedVerticalScrollBarVisibility;
                this._lastVisiblityH = this.scrollView.ComputedHorizontalScrollBarVisibility;
                if (this.scrollView.ComputedVerticalScrollBarVisibility == Visibility.Visible)
                {
                    num2 = 20.0;
                }
                else
                {
                    num2 = 5.0;
                }
                if (this.scrollView.ComputedVerticalScrollBarVisibility == Visibility.Visible)
                {
                    num = 20.0;
                }
                else
                {
                    num = 5.0;
                }
                this.msgList.Margin = new Thickness(0.0, 0.0, num2, num);
            }
        }

        public static void SetMsg(ObservableCollection<ShowMsg> infos, MediaElement mp3, StackPanel panelList)
        {
            if (infos.Count >= 1)
            {
                mp3.Play();
                panelList.Children.Clear();
                foreach (ShowMsg msg in infos)
                {
                    panelList.Children.Add(new Notification(msg));
                }
            }
        }

        public static MediaElement MainMediaElement
        {
            get;
            set;
        }

        public static StackPanel MainStackPanel
        {
            get;
            set;
        }

        private static ObservableCollection<ShowMsg> ShowMsgs
        {
            get;
            set;
        }
    }
}
